package com.maddox.relax.helper;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.maddox.relax.helper.launcher.MLauncher;
import com.maddox.relax.listener.OnImageTakeCompleteListener;
import com.maddox.relax.model.ImageInfo;
import com.maddox.relax.util.FileUtils;
import com.maddox.relax.util.LogUtil;
import com.maddox.relax.util.PBitmapUtils;
import com.maddox.relax.util.PermissionUtils;
import com.maddox.relax.dialog.LoadindDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 拍照 拍视频 实际传参操作类
 */
public class CameraCompat {
    //保存照片的文件目录名
    public static final String FILE_IMAGE_DIR = Environment.DIRECTORY_PICTURES;
    //保存视频的文件目录名
    public static final String FILE_VIDEO_DIR = Environment.DIRECTORY_MOVIES;
    private static LoadindDialog loadindDialog;

    /**
     * @param activity         调用拍照的页面
     * @param imageName        图片名称
     * @param completeListener 拍照的回调
     */
    public static void takePhoto(FragmentActivity activity, String imageName,OnImageTakeCompleteListener completeListener) {
        String imageDir = PBitmapUtils.getPickerFileDirectory(activity).getAbsolutePath();
        //存放照片的地址
        String imagePath = imageDir + File.separator + imageName;
        //检查权限
        boolean hasPermission = PermissionUtils.hasCameraPermissions(activity);
        if (!hasPermission || completeListener == null) {
            Toast.makeText(activity, "无权限或者拍照返回监听器", Toast.LENGTH_SHORT).show();
            return;
        }
        //获取图片存储的Uri地址
        Uri imageUri = PermissionUtils.getUriForFile(activity, new File(imagePath));
        MLauncher.init(activity).startActivityForResult(getIntentFromUri(imageUri), new MLauncher.CallBack() {
            @Override
            public void onActivityResult(int resultCode, Intent data) {
                if (resultCode != FragmentActivity.RESULT_OK || TextUtils.isEmpty(imagePath)) {
                    completeListener.onImageTakeComplete(null);
                    return;
                }
                if (loadindDialog == null) {
                    loadindDialog = new LoadindDialog(activity, "正在压缩...");
                }
                loadindDialog.show();
                Log.d("Maddox", "保存地址: " + imagePath);
                Log.d("Maddox", "保存路径: " + imageDir);
                Luban.with(activity)
                        .load(imagePath)
                        .ignoreBy(100)
                        .setTargetDir(imageDir)
                        .setRenameListener(s -> {
                            String substring = s.substring(s.lastIndexOf("/"));
                            String replace = substring.replace("IMG_", "IMG_CP_");
                            Log.d("Maddox", "重命名:" + replace);
                            return replace;
                        })
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                FileUtils.deleteFile(imagePath);
                                //处理图片,并进行压缩
                                ImageInfo imageInfo = new ImageInfo();
                                imageInfo.filePath = file.getAbsolutePath();
                                imageInfo.fileName = file.getName();
                                int[] size = PBitmapUtils.getImageWidthHeight(file.getAbsolutePath());
                                imageInfo.width = size[0];
                                imageInfo.height = size[1];
                                imageInfo.mimeType = "image/jpeg";
                                ArrayList<ImageInfo> list = new ArrayList<>();
                                list.add(imageInfo);
                                completeListener.onImageTakeComplete(list);
                                loadindDialog.dismiss();
                            }

                            @Override
                            public void onError(Throwable throwable) {
                                Log.d("Maddox", "出现异常-->" + throwable);
                                completeListener.onImageTakeComplete(null);
                                loadindDialog.dismiss();
                            }
                        }).launch();


            }
        });


    }

    /**
     * 调起系统相机录制视频
     * @param activity
     * @param completeListener
     */
    public static void takeVideo(FragmentActivity activity,String filename,OnImageTakeCompleteListener completeListener){
        String videoDir = PBitmapUtils.getVideoFileDirectory(activity).getAbsolutePath();
        //存放视频的地址
        String videoPath = videoDir + File.separator + filename;
        boolean hasPermission = PermissionUtils.hasCameraPermissions(activity);
        if (!hasPermission || completeListener == null) {
            Toast.makeText(activity, "无权限调用相机", Toast.LENGTH_SHORT).show();
            return;
        }
        Uri videoUri = PermissionUtils.getUriForFile(activity, new File(videoPath));
        MLauncher.init(activity).startActivityForResult(getVideoIntentFromUri(videoUri),(int resultCode, Intent data)->{

            if (resultCode != FragmentActivity.RESULT_OK || TextUtils.isEmpty(videoPath)) {
                completeListener.onImageTakeComplete(null);
                return;
            }
//            if (loadindDialog == null) {
//                loadindDialog = new LoadindDialog(activity, "正在读取...");
//            }
//            loadindDialog.show();
            LogUtil.d( "视频保存地址: " + videoPath);
            ImageInfo imageInfo = new ImageInfo();
            imageInfo.fileName = filename;
            imageInfo.filePath = videoPath;
//            loadindDialog.dismiss();
            completeListener.onImageTakeComplete(new ArrayList<ImageInfo>(){{add(imageInfo);}});
        });

    }


    private static Intent getIntentFromUri(Uri imageUri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        return intent;
    }

    private static Intent getVideoIntentFromUri(Uri videoUri) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        return intent;
    }




}
